import cv2
import os

def del_file(path: str):
    """
    清空图片输出目录
    """
    del_list = os.listdir(path)
    for f in del_list:
        file_path = os.path.join(path, f)
        if os.path.isfile(file_path):
            os.remove(file_path)

def video_to_images(path: str, fps_step: int=24, file_index: int=0) -> None:
    """
    path: 视频文件地址
    fps_step: 每隔几帧保存一张，默认 24
    """
    start_time = 0
    cv = cv2.VideoCapture(path)   # 打开视频文件
    cv.set(cv2.CAP_PROP_POS_MSEC, start_time * 1000)    # 跳过片头

    fps = cv.get(cv2.CAP_PROP_FPS)  # 获取帧率
    frame_count = int(cv.get(cv2.CAP_PROP_FRAME_COUNT)) # 获取总帧数
    duration = int(frame_count / fps)
    end_time = duration - 60

    if not cv.isOpened():
        # 视频文件打开状态检查
        print('视频文件打开失败，请检查视频文件是否存在。')
        exit(0)
    if not os.path.exists('images/'):
        # 图片输出目录存在检查，如不存在则创建
        os.mkdir('images/')
    else:
        # 图片输出目录若存在，则清空文件夹
        del_file('images/')
    
    order = file_index
    fps = 0
    while True:
        fps += 1
        rval, frame = cv.read()
        current_time = cv.get(cv2.CAP_PROP_POS_MSEC) / 1000
        if current_time > end_time:
            break
        if fps == fps_step:
            fps = 0
            order += 1
            if rval:
                cv2.imwrite('./images/'+str(order)+'.jpeg', frame)  # 图片保存方式/命名/图片格式
                cv2.waitKey(1)
            else:
                break
    cv.release()
    print('>>> Step.1 视频文件转图片文件保存成功.')
video_to_images('/Users/aolic/Desktop/海绵宝宝第01季/S01-01急征店员+海底清洁队+我的好朋友.mp4')